package client.comm.commlib.network

import client.comm.commlib.utils.SharedUtil
import client.comm.commlib.utils.Util
import okhttp3.Credentials
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
import java.net.Proxy
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.*
import java.util.concurrent.TimeUnit
import javax.net.ssl.*
import kotlin.Comparator

class XxRetroHttp private constructor() {
    private val mRetrofit: Retrofit by lazy {
        val okHttpClient = OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.SECONDS)
            .writeTimeout(7, TimeUnit.SECONDS)
            .readTimeout(7, TimeUnit.SECONDS)
            .proxy(Proxy.NO_PROXY)
            //https支持
//            .hostnameVerifier { hostname, session -> true }
//            .sslSocketFactory(getSSLFactory(),initTrustManager())  //备用方案：initSSLSocketFactory()替代getSSLFactory()

            .addInterceptor(object : Interceptor {
                @Throws(IOException::class)
                override fun intercept(chain: Interceptor.Chain): Response {


//                        String androidID = Utils.INSTANCE.getAndroidID();
                    var httpUrl = chain.request().url
                    val builder = httpUrl.newBuilder()
                    if (httpUrl.encodedPath.startsWith("/oauth/2.0/token")) {

                    } else {
                        val count = httpUrl.querySize
                        val keys =
                            arrayOfNulls<String>(4 + count)
                        val ts = System.currentTimeMillis().toString()
                        builder.addQueryParameter("ys", ts)
                        keys[0] = "ys$ts"
                        builder.addQueryParameter("appkey", "9f0ea890670b472d9cddc0866e8a3b17")
                        keys[1] = "appkey" + "9f0ea890670b472d9cddc0866e8a3b17"

                        val token = SharedUtil.read("token", "")
                        builder.addQueryParameter("session", token)
                        keys[2] = "session" + token

                        builder.addQueryParameter("res_id", "a80306cc61744099a2966696e2c80b7d")
                        keys[3] = "res_ida80306cc61744099a2966696e2c80b7d"

                        if (count > 0) {
                            var index = 4
                            for (i in 0 until count) {
                                val name = httpUrl.queryParameterName(i)
                                val value = httpUrl.queryParameterValue(i)
                                keys[index] = name + value
                                index++
                            }
                        }
                        Arrays.sort(
                            keys,
                            object : Comparator<String?> {
                                //内部类
                                override fun compare(o1: String?, o2: String?): Int {
                                    return o1!!.compareTo(o2!!)
                                }
                            })
                        val stringBuilder = StringBuilder()
                        for (data in keys) {
                            stringBuilder.append(data)
                        }
                        val string: String = Util.genHMAC(
                            stringBuilder.toString(),
                            "015b6845db5540eeaf6d13aae33b4127"
                        )
                        builder.addQueryParameter("signature", string)
                    }

                    httpUrl = builder.build()


                    val request = chain.request().newBuilder()
                        .addHeader("Content-Type", "application/x-www-form-urlencoded")
                        .addHeader(
                            "Authorization",
                            Credentials.basic(
                                "9f0ea890670b472d9cddc0866e8a3b17",
                                "015b6845db5540eeaf6d13aae33b4127"
                            )
                        ) // 第一个是公钥,第二个是私钥
                        .url(httpUrl)
                        .build()
                    return chain.proceed(request)
                }
            })
            .build()

        Retrofit.Builder()
            .baseUrl(HhRetroHttp.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(okHttpClient)
            .build()
    }


    companion object {
//        val API_URL = "http://123.56.78.60/"
//        val HH_URL = "http://123.56.78.60:5000/"
        private val INSTANT: XxRetroHttp by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { XxRetroHttp() }

        fun get(): XxRetroHttp {
            return INSTANT
        }

        fun <T> createApi(tClass: Class<T>): T {
            return lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { get().mRetrofit.create(tClass)}.value
        }
    }


    /**
     * 绕过验证
     * @return
     */
//    fun createIgnoreVerifySSL(sslVersion: String): SSLSocketFactory {
//        var sc = SSLContext.getInstance(sslVersion);
//        val trustAllCerts: Array<TrustManager> = arrayOf(object : X509TrustManager {
//            @Throws(CertificateException::class)
//            override fun checkClientTrusted(
//                chain: Array<X509Certificate>, authType: String
//            ) {
//            }
//
//            @Throws(CertificateException::class)
//            override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
//            }
//
//            override fun getAcceptedIssuers(): Array<X509Certificate?> {
//                return arrayOfNulls(0)
//            }
//        })
//
//        sc!!.init(null, trustAllCerts, java.security.SecureRandom())
//        // Create all-trusting host name verifier
//        val allHostsValid = HostnameVerifier { _, _ -> true }
//        /***
//         * 如果 hostname in certificate didn't match的话就给一个默认的主机验证
//         */
//        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
//        return sc.socketFactory;
//    }


}